<script setup lang="ts">
import { PropType, reactive, ref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'

import { required } from '@/utils/formRules'

// import { adminFaPastureListApi } from '@/api/fa/pasture'
import { sysDictRelsApi } from '@/api/dict'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { spEnclosureListApi } from '@/api/fa/enclosure'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

/****************************** 变量 start ******************************/
const data = ref<any>({})
const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举
const rules = reactive({
  earcon_code: [required],
  asset_code: [required],
  enclosure_id: [required],
  sex: [required],
  month_age: [required]
})

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})
console.log(props, dict)
/****************************** 组件参数 end ******************************/

// 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    data.value = await props.currentRow
    // 明细信息处理一下，加上d_id
    await methods.setValues(data.value)
    const res = await spEnclosureListApi({})
      .catch(() => {})
      .finally(() => {})
    if (res) {
      // listData.value = res.data
      newTreeData.value = [{ id: '0', name: '=== 顶级 ===' }, ...res.data]
      // listData.value = res.data
    }
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  await breedGetSub(value)
  let formData = await methods.getFormData()
  await methods.setValues({ ...formData, breed_sub: '' })
}

// const onCustomer = async () => {
//   data.value.detailedData = [] // 删除明细的数据
// }
const newTreeData = ref<any[]>([])

const schema: any = [
  // {
  //   field: 'customer_id',
  //   label: '所属牧场',
  //   component: 'DialogRefer',
  //   componentProps: {
  //     getListApi: adminFaPastureListApi,
  //     response: { count: 'count', data: 'data' },
  //     title: '选择创建人（双击选择）',
  //     nameField: 'customer_name',
  //     relNameField: 'name',
  //     valueField: 'id',
  //     crudSchemas: [
  //       { field: 'name', label: '牧场名称', search: { show: true } },
  //       { field: 'code', label: '牧场编码', search: { show: true } }
  //     ],
  //     modelName: data.value.customer_name,
  //     onChange: onCustomer
  //   }
  // },
  {
    field: 'number',
    label: '牲畜数量',
    component: 'Input',
    colProps: {
      span: 10
    },
    componentProps: {
      disabled: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    component: 'Select',
    colProps: {
      span: 10
    },
    componentProps: {
      options: dict.breed,
      onChange: breedChange
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    component: 'Select',
    colProps: {
      span: 10
    },
    componentProps: {
      options: breedSubData
    }
  },
  {
    field: 'purpose',
    label: '用途',
    component: 'Select',
    componentProps: {
      options: dict.purpose,
      disabled: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    component: 'Input',
    colProps: {
      span: 10
    }
  },
  {
    field: 'asset_code',
    label: '资产编号',
    component: 'Input',
    colProps: {
      span: 10
    }
  },
  {
    field: 'enclosure_id',
    label: '栏位',
    component: 'TreeSelect',
    colProps: {
      span: 10
    },
    componentProps: {
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'id',
      props: {
        children: 'children',
        label: 'name'
      }
    }
  },
  {
    field: 'sex',
    label: '性别',
    component: 'Select',
    componentProps: {
      options: dict.animal_sex
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    component: 'Input',
    colProps: {
      span: 10
    }
  }
]
const { register, methods, elFormRef } = useForm({
  schema: schema
})

const getFormData = async () => {
  let formData = await methods.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData }
}

defineExpose({
  elFormRef,
  getFormData
})

/****************************** 初始化 start ******************************/
const init = async () => {
  // 获取关联关系
  await getDictRels()
  // 调用查看接口查询数据
  await getMedicalOrderSee()
  // 跟新畜别
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
}
init()
/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="register" />
    </ContentWrap>
  </div>
</template>
